package com.ruoyi.web.controller.an;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/an-media")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${ruoyi.profile}")
    private String rootPath;

    /**
     * 查询产品配件品类列表
     */
    @GetMapping(value = "/images/**", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] scale(HttpServletRequest request) throws Exception {
        String paths =
                request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        String path = paths.replace("/", "\\");
        FileUtil.mkdir(rootPath);
        String imgPath = rootPath + path;
        imgPath = imgPath.replace("\\an-media", "");
        File file = FileUtil.file(imgPath);
//        System.out.println(imgPath);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        inputStream.close();
        return bytes;
    }


    /**
     * 查询产品配件品类列表
     */
    @GetMapping(value = "/excel/**")
    public void excel(HttpServletRequest request, HttpServletResponse response) {
        String paths =
                request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        String path = paths.replace("/", "\\");
        // 将face.jpg切割为原型保存为face_radis.png
        String rootPath = System.getProperty("rootPath");
        String imgPath = rootPath + path;
        File file = FileUtil.file(imgPath);
        try
        {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            inputStream.close();
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName() + "");
            response.addHeader("Content-Length", "" + bytes.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            OutputStream os = response.getOutputStream();
            os.write(bytes);
            //先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();
        }catch (Exception e)
        {
            log.error(e.getMessage());
            throw new RuntimeException("文件读取失败！");
        }
    }


    @PostMapping(value = "/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        try
        {
            String path = uploadMultipartFile(multipartFile);
            return AjaxResult.success(path);
        }catch (Exception e)
        {
            log.error(e.getMessage());
            return AjaxResult.error("上传文件失败！");
        }
    }

    public String uploadMultipartFile(MultipartFile file) throws IOException {
        String uploadName = file.getOriginalFilename().replace("./upload/", "");
        String type = getType(uploadName);
        File uploadFile = FileUtil.file(rootPath + "/images/" + DateUtils.getNowDate().getTime() * 2 + "." + type);
        if (!FileUtil.exist(uploadFile.getParent())) {
            uploadFile.mkdirs();
        }
        file.transferTo(uploadFile);
        String resultPath = "/an-media/images/" + uploadFile.getName();
        return resultPath;
    }


    public static String getType(String filename) {
        String typeName = "";
        if (filename.contains("xlsx")) {
            typeName = "xlsx";
        } else if (filename.contains("xls")) {
            typeName = "xls";
        } else {
            typeName = filename.split("\\.")[1];
        }
        return typeName;
    }
}
